package com.cuitrip.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

import com.cuitrip.app.MainApplication;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ak
 */
public class MediaFetcher {

    // 启动图片库App
    public static boolean launchPictureManagerForResult(Activity activity, int requestCode) {
        if (null == activity)
            return false;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        try {
            activity.startActivityForResult(intent, requestCode);
            return true;
        } catch (Exception e) {
//            .e(e.getMessage());
        }
        return false;
    }

    // 启动相机App
    public static String launchCameraManagerForResult(Activity activity, int requestCode) {
        if (null == activity)
            return null;
        SimpleDateFormat imageNameFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String imageName = imageNameFormat.format(new Date());
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, imageName);
        Uri imageUri = null;
        String imagePath = null;
        try {
            imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            imagePath = getRealImagePathFromURI(imageUri, activity.getContentResolver());
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            activity.startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            return null;
        }
        return imagePath;
    }

    // 启动图片库App
    public static boolean launchPictureManagerForResult(Fragment fragment, int requestCode) {
        if (null == fragment)
            return false;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        try {
            fragment.startActivityForResult(intent, requestCode);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    // 启动相机App
    public static String launchCameraManagerForResult(Fragment fragment, int requestCode) {
        if (null == fragment)
            return null;
        SimpleDateFormat imageNameFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String imageName = imageNameFormat.format(new Date());
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, imageName);
        Uri imageUri = null;
        String imagePath = null;
        try {
            imageUri = MainApplication.getInstance().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            imagePath = getRealImagePathFromURI(imageUri, MainApplication.getInstance().getContentResolver());
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            fragment.startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            return null;
        }
        return imagePath;
    }

    // 解析获取图片库图片Uri物理路径
    public static String parsePicturePath(Context context, Uri uri) {
        if (null == context || null == uri)
            return null;
        boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentUri
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageDocumentsUri
            if (isExternalStorageDocumentsUri(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] splits = docId.split(":");
                String type = splits[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + File.separator + splits[1];
                }
            }
            // DownloadsDocumentsUri
            else if (isDownloadsDocumentsUri(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaDocumentsUri
            else if (isMediaDocumentsUri(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = "_id=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosContentUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;

    }

    private static String getRealImagePathFromURI(Uri uri, ContentResolver resolver) {
        Cursor cursor = null;
        String path = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = resolver.query(uri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            path = cursor.getString(column_index);
        } catch (IllegalArgumentException e) {
        } finally {
            try {
                if (cursor != null)
                    cursor.close();
            } catch (Exception e) {
            }
        }
        return path;
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = "_data";
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            try {
                if (cursor != null)
                    cursor.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    private static boolean isExternalStorageDocumentsUri(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocumentsUri(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocumentsUri(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static boolean isGooglePhotosContentUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static File getImageDir(Context context) throws Exception {
        File cacheDir = getCacheDir(context);
        if (cacheDir == null) {
            return null;
        }
        File dir = new File(cacheDir.getAbsolutePath().concat("/img"));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    public static File getTempImageFilePath(Context context) {
        try{
            File cacheDir = getCacheDir(context);
            if (cacheDir == null) {
                return null;
            }
            File dir = new File(cacheDir.getAbsolutePath().concat("/img"));
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File tempImageFile = new File(dir,"temp");
            return tempImageFile;
        }catch (Exception e){

        }
        return null;
    }

    @SuppressLint("NewApi")
    public static File getCacheDir(Context context) {
        if (context == null) return null;
        int sdk = Build.VERSION.SDK_INT;
        File file = null;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (sdk < 8) {
                file = new File(Environment
                        .getExternalStorageDirectory()
                        .getAbsolutePath()
                        .concat("/Android/data/" + context.getPackageName()
                                + "/cache/"));
            } else {
                try {
                    file = context.getExternalCacheDir();
                } catch (SecurityException se) {
                    se.printStackTrace();
                    file = new File(Environment
                            .getExternalStorageDirectory()
                            .getAbsolutePath()
                            .concat("/Android/data/" + context.getPackageName()
                                    + "/cache/"));
                }
            }
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            //throw new Exception();
        } else {
            //throw new ExternalStorageException("external storage is not mounted");
        }
        if (file != null) {
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            //throw new ExternalStorageException("can't find a cache dir");
        }
        return file;
    }


}
